package com.walker.controller.catalogue;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.walker.anno.ResponseResult;
import com.walker.handler.ResponseData;
import com.walker.service.catalogue.CatalogueDataTableService;
import com.walker.util.CommonUtils;

import net.sf.json.JSONObject;

/**
 * 资产-目录-数据表
 */
@RestController
@RequestMapping(value = "/catalogueDataTable")
@ResponseResult
public class CatalogueDataTableController {
	
	private static final Log log = LogFactory.getLog(CatalogueDataTableController.class);
	
	@Resource
	private CatalogueDataTableService service;
	
	/**
	 *数据表列表 
	 * @param login_code
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@PostMapping("listPage")
	@ResponseResult(msg="doNotOperateReturnResult")
	public String listPage(@RequestHeader(value = "login_code") String login_code,@RequestBody String request) {
		Map<String, Object> params = JSONObject.fromObject(request);
		JSONObject json = new JSONObject();
		try{
			json.put("data", service.listPage(params, login_code));
			json.put("totalRecords", Long.parseLong(service.listCount(params)));
			json.put("flag",true);
		}catch(Exception e){
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
			json.put("flag", false);
			json.put("msg", e.getMessage());
		}
		return json.toString();
	}
	
	/**
	 * 查询数据表详情
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@PostMapping("queryById")
	@ResponseResult(msg="doNotOperateReturnResult")
	public String queryById(@RequestHeader(value = "login_code") String login_code,@RequestBody String request) {
		Map<String, Object> params = JSONObject.fromObject(request);
		JSONObject json = new JSONObject();
		try{
			Map<String,Object> data = service.queryById(params, login_code);
			json.putAll(data);
			json.put("flag",true);
		}catch(Exception e){
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
			json.put("flag", false);
			json.put("msg", e.getMessage());
		}
		return json.toString();
	}
	
	/**
	 * 分区信息
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@PostMapping("getPartitionInfo")
	@ResponseResult(msg="doNotOperateReturnResult")
	public String getPartitionInfo(@RequestBody String request) {
		Map<String, Object> params = JSONObject.fromObject(request);
		JSONObject json = new JSONObject();
		try{
			Map<String,Object> data = service.getPartitionInfo(params);
			json.put("data",data.get("partitions"));
			json.put("columns",data.get("columns"));
			json.put("flag",true);
		}catch(Exception e){
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
			json.put("flag",false);
			json.put("msg",e.getMessage());
		}
		return json.toString();
	}
	
	/**
	 * 产出信息
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@PostMapping("getOutputInfo")
	public Map<String, Object> getOutputInfo(@RequestBody String request) {
		Map<String, Object> params = JSONObject.fromObject(request);
		return service.getOutputInfo(params);
	}
	
	
	/**
	 * 数据预览
	 * @param login_code
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@PostMapping("previewData")
	@ResponseResult(msg="doNotOperateReturnResult")
	public String previewData(@RequestHeader(value = "login_code") String login_code,@RequestBody String request) {
		JSONObject json = new JSONObject();
		Map<String, Object> params = JSONObject.fromObject(request);
		try {
			Map<String, Object> data = service.previewData(params,login_code);

			json.put("columns", data.get("columns"));
			json.put("data", data.get("data"));
			json.put("flag", true);
		} catch (Exception e) {
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
			json.put("flag", false);
			json.put("msg", e.getMessage());
		}
		return json.toString();
	}
	
	/**
	 * 血缘信息
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@PostMapping("consanguinity")
	public Map<String,Object> consanguinity(@RequestBody String request) {
		Map<String, Object> params = JSONObject.fromObject(request);
		String cube_id = CommonUtils.valueOf(params.get("cube_id"));
		String isTemp = CommonUtils.valueOf(params.get("isTemp"));
		String source_type = CommonUtils.valueOf(params.get("source_type"));
		//String project_code = CommonUtils.valueOf(params.get("project_code"));
		Map<String, Object> data = new HashMap<String,Object>();
		if(StringUtils.equalsIgnoreCase(source_type, "hive")){
			data = service.consanguinity(cube_id, isTemp);
		}
		return data;
	}
	
	/**
	 * 收藏/取消收藏
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@PostMapping("setCollect")
	public ResponseData setCollect(@RequestHeader(value = "login_code") String login_code,@RequestBody String request) {
		Map<String, Object> params = JSONObject.fromObject(request);
		service.setCollect(params,login_code);
		return ResponseData.success("操作成功");
	}
	
	/**
	 * 数据表影响
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@PostMapping("queryTableEffectList")
	public Map<String, Object> queryTableEffectList(@RequestBody String request) {
		Map<String, Object> params = JSONObject.fromObject(request);
		return service.queryTableEffectList(params);
	}
	
	/**
	 * 集成同步影响
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@PostMapping("queryCorpusSyncEffectList")
	public Map<String, Object> queryCorpusSyncEffectList(@RequestBody String request) {
		Map<String, Object> params = JSONObject.fromObject(request);
		return service.queryCorpusSyncEffectList(params);
	}
	
	/**
	 * 使用说明查询
	 * @param request
	 * @return
	 */
	@PostMapping("queryByCubeId")
	public Map<String, Object> queryByCubeId(@RequestBody String cube_id) {
		return service.queryByCubeId(cube_id);
	}
	
	/**
	 * 存储类型
	 * @return
	 */
	@PostMapping("getSourceType")
	public List<Map<String, Object>> getSourceType() {
		return service.getSourceType();
	}
	
	/**
	 * 使用说明保存
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@PostMapping("saveUseDesc")
	public ResponseData saveUseDesc(@RequestBody String request) {
		Map<String, Object> params = JSONObject.fromObject(request);
		service.saveUseDesc(params);
		return ResponseData.success("保存成功");
	}
	
	/**
	 * 使用说明编辑
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@PostMapping("editUseDesc")
	public ResponseData editUseDesc(@RequestBody String request) {
		Map<String, Object> params = JSONObject.fromObject(request);
		service.editUseDesc(params);
		return ResponseData.success("编辑成功");
	}
	
	/**
	 * 使用说明删除
	 * @param request
	 * @return
	 */
	@PostMapping("deleteUseDesc")
	public ResponseData deleteUseDesc(@RequestBody String cube_id) {
		service.deleteUseDesc(cube_id);
		return ResponseData.success("删除成功");
	}
	
	/**
	 * 表类型
	 * @return
	 */
	@PostMapping("queryObjectType")
	public List<Map<String,Object>> queryObjectType() {
		return service.queryObjectType();
	}
	
	/**
	 * 元数据表
	 * @return
	 */
	@PostMapping("queryMetaTable")
	public List<Map<String,Object>> queryMetaTable(@RequestBody String project_code) {
		return service.queryMetaTable(project_code);
	}
	
	/**
	 * 元数据同步
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@PostMapping("metaSync")
	public ResponseData metaSync(@RequestBody String request) {
		Map<String, Object> params = JSONObject.fromObject(request);
		service.metaSync(params);
		return ResponseData.success("刷新成功");
	}
	
	/**
	 * 字段信息导出
	 * @param loginName
	 * @param cube_id
	 * @param source_type
	 * @return
	 */
	@PostMapping("/exportColums")
	@ResponseResult(msg="doNotOperateReturnResult")
	public ResponseEntity<InputStreamResource> exportColums(@RequestHeader(value = "login_code") String loginName,String cube_id,String source_type) {
		try {
			String cube_code = (String) service.queryById(cube_id,loginName).get("cube_code");

			HSSFWorkbook wb = new HSSFWorkbook();
			// 根据页面index 获取sheet页
			HSSFSheet sheet = wb.createSheet(cube_code);
			// 表头
			HSSFRow row = sheet.createRow(0);
			// 创建HSSFCell对象 设置单元格的值
			row.createCell(0).setCellValue("英文字段名");
			row.createCell(1).setCellValue("字段名称");
			row.createCell(2).setCellValue("数据类型");

			List<Map<String, Object>> columns = service.getColumns(cube_id,source_type);

			for (int i = 0; i < columns.size(); i++) {
				Map<String, Object> c = columns.get(i);
				// 创建HSSFRow对象
				row = sheet.createRow(i + 1);
				// 创建HSSFCell对象 设置单元格的值
				row.createCell(0).setCellValue(c.get("element_code").toString());
				row.createCell(1).setCellValue(c.get("element_name").toString());
				row.createCell(2).setCellValue(c.get("element_type").toString());
			}

			ByteArrayOutputStream baos = null;
			baos = new ByteArrayOutputStream();
			wb.write(baos);
			byte[] byt = baos.toByteArray();
			InputStream input = new ByteArrayInputStream(byt);

			HttpHeaders headers = new HttpHeaders();
			headers.add("Cache-Control", "no-cache, no-store, must- revalidate");
			headers.add("Pragma", "no-cache");
			headers.add("Expires", "0");

			return ResponseEntity.ok().headers(headers)
					.contentType(MediaType.parseMediaType("application/octet-stream"))
					.body(new InputStreamResource(input));

		} catch (Exception e) {
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
		} 
		return null;
	}
}